import React, { createRef } from 'react'
import { TOKEN } from '@/Utils/CONST'

export function AuthenticatedLink({ url, filename, children }) {
  const link = createRef()

  const handleAction = async() => {
    if (link.current.href) { return }

    let token = localStorage.getItem(TOKEN)
    const result = await fetch(url, {
      headers: {
        authorization: `Bearer ${token}`,
      },
    })

    const blob = await result.blob()
    const href = window.URL.createObjectURL(blob)

    link.current.download = filename
    link.current.href = href

    link.current.click()
  }

  return (
    <a role="button" ref={link} onClick={handleAction}>{children}</a>
  )
}
